import 'package:home_framework/api/upload_service.dart';

class DynamicEntity {
  static const IMAGE_BASE_URL = UploadService.uploadBaseUrl + 'image' + '/';
  late String _title;
  late String _imageUrl;
  late int _viewCount;
  late String _id;
  late String _content;

  String get title => _title;
  set title(value) => _title = value;

  String get imageUrl => _imageUrl;
  set imageUrl(value) => _imageUrl = IMAGE_BASE_URL + value;

  int get viewCount => _viewCount;
  set viewCount(value) => _viewCount = value;

  String get content => _content;
  set content(value) => _content = value;

  String get id => _id;

  static DynamicEntity fromJson(Map<String, dynamic> json) {
    DynamicEntity newEntity = DynamicEntity();
    newEntity._id = json['_id'];
    newEntity._title = json['title'];
    newEntity._imageUrl = json['imageUrl'];
    // 兼容旧的后端mock产生的数据，后续统一返回图片文件 id。
    if (!newEntity._imageUrl.startsWith('http')) {
      newEntity._imageUrl = IMAGE_BASE_URL + newEntity._imageUrl;
    }
    newEntity._viewCount = json['viewCount'] ?? 0;
    newEntity._content = json['content'];

    return newEntity;
  }

  void updateByJson(Map<String, dynamic> json) {
    _title = json['title'] ?? _title;
    _content = json['title'] ?? _content;
    _imageUrl = json['imageUrl'] != null
        ? IMAGE_BASE_URL + json['imageUrl']
        : _imageUrl;
  }
}
